<template>
  <div>
   <!-- 面包屑导航 -->
   <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
   </el-breadcrumb>
   <!-- 卡片视图区域 -->
   <el-card>
      <!-- 头部警告区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" :closable="false" show-icon />
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
         <el-col>
            <span>选择商品分类：</span>
            <!-- 商品分类级联选择框 -->
            <el-cascader
               v-model="selectedCateKeys"
               :options="cateList"
               :props="cateprops"
               @change="handleChange">
            </el-cascader>
         </el-col>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
         <el-tab-pane label="动态参数" name="many">
            <!-- 动态参数面板 -->
            <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="addDialogVisible = true">添加参数</el-button>
            <!-- 动态参数表格 -->
            <el-table :data="manyTableData" border stripe>
               <!-- 展开行操作 -->
               <el-table-column type="expand">
                 <template slot-scope="scope">
                   <!-- 循环渲染tag -->
                   <el-tag
                   v-for="(item,index) in scope.row.attr_vals"
                   :key="index"
                   closable
                   @close="handleClose(index, scope.row)">{{item}}</el-tag>
                   <!-- 输入文本框 -->
                   <el-input
                     class="input-new-tag"
                     v-if="scope.row.inputVisible"
                     v-model="scope.row.inputValue"
                     ref="saveTagInput"
                     size="small"
                     @keyup.enter.native="handleInputConfirm(scope.row)"
                     @blur="handleInputConfirm(scope.row)"
                   >
                   </el-input>
                   <!-- 添加按钮 -->
                   <el-button
                   v-else
                   class="button-new-tag"
                   size="small"
                   @click="showInput(scope.row)">+ New Tag</el-button>
                 </template>
               </el-table-column>
               <el-table-column type="index"></el-table-column>
               <el-table-column label="参数名称" prop="attr_name"></el-table-column>
               <el-table-column label="操作">
                  <template slot-scope="socpe">
                     <el-button
                     type="primary"
                     icon="el-icon-edit"
                     size="mini"
                     @click="showEditDialog(socpe.row.attr_id)">编辑</el-button>
                     <el-button
                     type="danger"
                     icon="el-icon-delete"
                     size="mini"
                     @click="removeParams(socpe.row.attr_id)">删除</el-button>
                  </template>
               </el-table-column>
            </el-table>
         </el-tab-pane>
         <el-tab-pane label="静态属性" name="only">
            <!-- 静态属性面板 -->
            <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="addDialogVisible = true">添加属性</el-button>
            <!-- 静态属性表格 -->
            <el-table :data="onlyTableData" border stripe>
               <!-- 展开行操作 -->
               <el-table-column type="expand">
                 <template slot-scope="scope">
                   <!-- 循环渲染tag -->
                   <el-tag
                   v-for="(item,index) in scope.row.attr_vals"
                   :key="index"
                   closable
                   @close="handleClose(index, scope.row)">{{item}}</el-tag>
                   <!-- 输入文本框 -->
                   <el-input
                     class="input-new-tag"
                     v-if="scope.row.inputVisible"
                     v-model="scope.row.inputValue"
                     ref="saveTagInput"
                     size="small"
                     @keyup.enter.native="handleInputConfirm(scope.row)"
                     @blur="handleInputConfirm(scope.row)"
                   >
                   </el-input>
                   <!-- 添加按钮 -->
                   <el-button
                   v-else
                   class="button-new-tag"
                   size="small"
                   @click="showInput(scope.row)">+ New Tag</el-button>
                 </template>
               </el-table-column>
               <el-table-column type="index"></el-table-column>
               <el-table-column label="参数名称" prop="attr_name"></el-table-column>
               <el-table-column label="操作">
                  <template slot-scope="socpe">
                     <el-button
                     type="primary"
                     icon="el-icon-edit"
                     size="mini"
                     @click="showEditDialog(socpe.row.attr_id)">编辑</el-button>
                     <el-button
                     type="danger"
                     icon="el-icon-delete"
                     size="mini"
                     @click="removeParams(socpe.row.attr_id)">删除</el-button>
                  </template>
               </el-table-column>
            </el-table>
         </el-tab-pane>
      </el-tabs>
   </el-card>
   <!-- 添加参数对话框 -->
   <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed">
      <!-- 添加参数表单 -->
      <el-form
      :model="addForm"
      :rules="addFormRules"
      ref="addFormRef"
      label-width="100px">
         <el-form-item :label="titleText" prop="attr_name">
           <el-input v-model="addForm.attr_name"></el-input>
         </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
  </el-dialog>
  <!-- 修改参数对话框 -->
  <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed">
      <!-- 添加参数表单 -->
      <el-form
      :model="editForm"
      :rules="editFormRules"
      ref="editFormRef"
      label-width="100px">
         <el-form-item :label="titleText" prop="attr_name">
           <el-input v-model="editForm.attr_name"></el-input>
         </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
  </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'params',
  data() {
    return {
      cateList: [],
      // 配置级联选择框
      cateprops: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 级联选择框选择的keys数组
      selectedCateKeys: [],
      // 激活页签名称
      activeName: 'many',
      // 动态参数数据
      manyTableData: [],
      // 静态属性数据
      onlyTableData: [],
      // 添加参数对话框显示
      addDialogVisible: false,
      // 添加参数表单对象
      addForm: {
        attr_name: ''
      },
      // 添加参数表单验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数', trigger: 'blur' }
        ]
      },
      // 修改对话框显示
      editDialogVisible: false,
      // 需要编辑的数据
      editForm: {},
      // 编辑表单验证规则
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数', trigger: 'blur' }
        ]
      },
      // 控制文本输入框的显示
      inputVisible: false,
      // 文本输入框内容
      inputValue: ''
    }
  },
  computed: {
    // 添加按钮是否可用
    isBtnDisable() {
      // 按钮是否禁用，禁用返回true
      if (this.selectedCateKeys.length !== 3) return true
      return false
    },
    // 当前选择的三级分类的id
    cateId() {
      if (this.selectedCateKeys.length == 3) return this.selectedCateKeys[2]
      return null
    },
    // 动态计算标题文本
    titleText() {
      if (this.activeName === 'many') return '动态参数'
      else return '静态属性'
    }
  },
  methods: {
    // 获取所有分类列表
    getCateList() {
      this.$http.get('categories')
        .then(res => {
          let result = res.data
          if (result.meta.status !== 200) return this.$message.error('获取分类失败')
          this.cateList = result.data
        })
    },
    // 获取参数数据
    getParamsData() {
      this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName }})
        .then(res => {
          let result = res.data
          if (result.meta.status !== 200) return this.$message.error('获取参数列表失败')
          result.data.forEach(item => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(' '):[]
            // 控制文本框显示隐藏
            item.inputVisible = false
            // 文本框输入
            item.inputValue = ''
          })
          if (this.activeName === 'many') this.manyTableData = result.data
          else this.onlyTableData = result.data
        })
    },
    // 级联选择框发生变化监听
    handleChange() {
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return this.$message.error('只能选择第三级')
      }
      // 当第三级选好的时候获取参数
      this.getParamsData()
    },
    // tab页签点击事件处理函数
    handleClick() {
      // 当面板切换的时候获取数据
      this.getParamsData()
    },
    // 添加对话框关闭事件监听
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击添加参数
    addParams() {
      this.$refs.addFormRef.validate(valid => {
        if (!valid) return
        this.$http.post(`categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }).then(res => {
          let result = res.data
          if (result.meta.status !== 201) return this.$message.error('添加参数失败')
          this.$message.success('添加成功')
          this.addDialogVisible = false
          this.getParamsData()
        })
      })
    },
    // 编辑对话框显示
    showEditDialog(attr_id) {
      this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`,
        { params: { attr_sel: this.activeName }})
        .then(res => {
          let result = res.data
          if (result.meta.status !== 200) return this.$message.error('获取参数信息失败')
          this.editForm = result.data
        })
      this.editDialogVisible = true
    },
    // 编辑对话框关闭事件监听
    editDialogClosed() {
      // 重置修改表单
      this.$refs.editFormRef.resetFields()
    },
    // 点击提交修改
    editParams() {
      this.$refs.editFormRef.validate(valid => {
        if (!valid) return
        this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        }).then(res => {
          let result = res.data
          if (result.meta.status !== 200) return this.$message.error('修改参数失败')
          this.$message.success('修改成功')
          this.getParamsData()
          this.editDialogVisible = false
        })
      })
    },
    // 点击删除参数
    removeParams(id) {
      this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
          .then(res => {
            let result = res.data
            if (result.meta.status !== 200) return this.$message.error('删除失败')
            this.getParamsData()
            this.$message.success('删除成功!')
          })
      }).catch(() => {
        this.$message.error('已取消删除')
      });
    },
    // 文本输入框失去焦点或者按下回车键
    handleInputConfirm(row) {
      row.inputVisible = false
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
        // 如果用户输入了空格，就直接返回
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 将输入的内容保存到服务器上
      this.saveAttrVals(row)
    },
    // 显示文本输入框
    showInput(row) {
      row.inputVisible = true
      // 文本框自动获得焦点
      this.$nextTick(() => {
        // 按了之后 dom还没有渲染完毕，所以要用$nextTick方法
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 删除标签
    handleClose(index, row) {
      row.attr_vals.splice(index, 1)
      this.saveAttrVals(row)
    },
    // 将attr_vals数据操作保存
    saveAttrVals(row) {
      this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        })
        .then(res => {
          let result = res.data
          if (result.meta.status !== 200) this.$message.error('修改失败')
          this.$message.success('修改成功')
        })
    }
  },
  created() {
    this.getCateList()
  },
}
</script>

<style lang="stylus" scoped>
.cat_opt
   margin 15px 0
.el-tag
   margin 0 10px
.input-new-tag
   width 120px
</style>
